﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Ymatou.User.Dto.Auth;
using YmtAuth.AppService.Model;
using YmtAuth.Dto;
using YmtSystem.CrossCutting;
using ServiceStack;
using System.Configuration;
using YmtAuth.Domain.Model.Safe;
namespace YmtAuth.AppService.ThirdPartyService
{
    public class LoginAuthResponse
    {
        public int Code { get; set; }
        public string AuthMessage { get; set; }

    }
    
    
    /// <summary>
    /// JAVA版的登录风控服务
    /// </summary>    
    public class UserSafeService
    {
        private static String JavaLoginAuthURL = String.Empty;

        static UserSafeService()
        {
            JavaLoginAuthURL = ConfigurationManager.AppSettings["JavaLoginAuthURL"];
        }

        public static ResponseData<LoginAuthResponse> LoginAuthExecute(int userId, String loginId, String appSource, String reqDomain, String deviceId, String clientId, String clientIp)
        {
            
            String _deviceid = String.IsNullOrEmpty(deviceId) ? clientId : deviceId;
            
            Dictionary<string, object> postData = new Dictionary<string, object>();
            postData.Add("UserId", userId);
            postData.Add("LoginId", loginId);
            postData.Add("AppSource", appSource);
            postData.Add("ReqDomain", reqDomain);
            postData.Add("DeviceId", _deviceid);
            postData.Add("ClientIp", clientIp);

            try
            {
                byte[] postDataBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(postData));//编码，尤其是汉字，事先要看下抓取网页的编码方式  
                WebClient webClient = new WebClient();
                webClient.Headers.Add("Content-Type", "application/json");//采取POST方式必须加的header，如果改为GET方式的话就去掉这句话即可 

                byte[] responseData = webClient.UploadData(JavaLoginAuthURL, "POST", postDataBytes);//得到返回字符流  
                string resJson = Encoding.UTF8.GetString(responseData);//解码  

                ResponseData<LoginAuthResponse> res = JsonConvert.DeserializeObject<ResponseData<LoginAuthResponse>>(resJson);

                return res;
            }
            catch (Exception ex)
            {
                YmatouLoggingService.Error(string.Format("[LoginAuthExecute] java error, userid: {0}, loginId: {1}, err: {2}", userId, loginId, ex.Message), ex);
                return ResponseData<LoginAuthResponse>.CreateSuccess(new LoginAuthResponse() {Code = 200});
            }
            
        }
    }
}
